package com.funo.wcity.app.controller;

import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.funo.wcity.app.entity.LoginUser;
import com.funo.wcity.app.entity.TblCompanies;
import com.funo.wcity.app.entity.TblMailDetail;
import com.funo.wcity.app.entity.TblUserMail;
import com.funo.wcity.app.service.SyncMail;
import com.funo.wcity.app.service.TblCompaniesService;
import com.funo.wcity.app.service.TblCompanyTypesService;
import com.funo.wcity.app.service.TblContactPersonsService;
import com.funo.wcity.app.service.TblMailAnnexService;
import com.funo.wcity.app.service.TblMailDetailService;
import com.funo.wcity.app.service.TblUserMailService;
import com.funo.wcity.app.utils.Constant;
import com.funo.wcity.app.utils.StringUtil;

@Controller
@SuppressWarnings("all")
public class TblMailDetailController extends CommonController{
	private static  Log log=LogFactory.getLog(TblMailDetailController.class); //日志
	@Resource(name="tblCompanyTypesService")
	private TblCompanyTypesService tblCompanyTypesService;
	@Resource(name="tblMailDetailService")
	private TblMailDetailService tblMailDetailService;
	@Resource(name="tblMailAnnexService")
	private TblMailAnnexService tblMailAnnexService;
	@Resource(name="syncMail")
	private SyncMail syncMail;
	@Resource(name="tblUserMailService")
	private TblUserMailService tblUserMailService;
	@Resource(name="tblContactPersonsService")
	private TblContactPersonsService tblContactPersonsService;
	@Resource(name="tblCompaniesService")
	private TblCompaniesService tblCompaniesService;
	/**
	 * 登入主界面
	 */
	@RequestMapping("/loginEnter")
	public String loginEnter(HttpServletRequest request,HttpServletResponse response){
		try{
			LoginUser loginUser=(LoginUser)request.getSession().getAttribute(Constant.LOGIN_USER);
			String path = request.getSession().getServletContext().getRealPath("")+ Constant.PATH;
			String contextPath=request.getContextPath();
			//查询帐号邮箱列表
			List<TblUserMail> userMailList=this.tblUserMailService.getTblUserMailList(loginUser.getIdUser());
			if(userMailList.size()>0){
				//默认获取第一个
				request.setAttribute("idUserMail", userMailList.get(0).getIdUserMail());
				request.setAttribute("userMailList",userMailList);
				this.syncMail.init(path, loginUser.getIdUser(),contextPath);
				new Thread(this.syncMail).start();//异步
			}
		}catch(Exception e){
			log.error("登入主界面失败，原因是："+e.getMessage(),e);
			return "web/opera_fail";
		}
		return "web/main";
	}  
	/**
	 * 收信 注：初始化收信操作
	 */
	@RequestMapping("/initMail")
	public String initMail(HttpServletRequest request,HttpServletResponse response){
		try{
			LoginUser loginUser=(LoginUser)request.getSession().getAttribute(Constant.LOGIN_USER);
			String path = request.getSession().getServletContext().getRealPath("")+ Constant.PATH;
			String contextPath=request.getContextPath();
			this.syncMail.init(path, loginUser.getIdUser(),contextPath);
			new Thread(this.syncMail).start();//异步
		}catch(Exception e){
			log.error("收信 注：初始化收信操作失败，原因是："+e.getMessage(),e);
			return "web/opera_fail";
		}
		return "web/opera_success";
	}
	/**
	 * 查询_收件箱/草稿箱/已发送/已删除/垃圾箱
	 */
	@RequestMapping("/listMailbox")
	public String listMailbox(HttpServletRequest request,HttpServletResponse response,Integer state,Integer pageNo,
			Integer idCompanyType, Integer idCompany, Integer idContactPerson,String queryStr) {
		try{
			LoginUser loginUser=(LoginUser)request.getSession().getAttribute(Constant.LOGIN_USER);
			if(StringUtil.isEmpty(pageNo)){
				pageNo=1;
			}
			String idEmployees=(String)request.getSession().getAttribute(Constant.LOGIN_EMPLOYEE);
			//查询所有公司类型
			List tblCompanyTypesList=this.tblCompanyTypesService.getTblCompanyTypesList(idEmployees);
			//添加陌生类型
			Map companyType=new HashMap();
			companyType.put("IDCOMPANYTYPE", "0");
			companyType.put("COMPANYTYPENAME", "陌生人");
			tblCompanyTypesList.add(companyType);
			request.setAttribute("tblCompanyTypesList", tblCompanyTypesList);
			//查询邮箱列表
			TblMailDetail tblMailDetail=new TblMailDetail();
			tblMailDetail.setState(state);
			tblMailDetail.setIdUser(loginUser.getIdUser());
			tblMailDetail.setIdCompanyType(idCompanyType+"");
			tblMailDetail.setIdCompany(idCompany+"");
			tblMailDetail.setIdContactPerson(idContactPerson+"");
			request.setAttribute("page",this.tblMailDetailService.getTbLMailDetailList(pageNo,Constant.DEFAULT_PAGE_SIZE, tblMailDetail,queryStr));
			request.setAttribute("tblMailDetail",tblMailDetail);
			request.setAttribute("idCompanyType",idCompanyType);
			request.setAttribute("idCompany",idCompany);
			request.setAttribute("idContactPerson",idContactPerson);
			request.setAttribute("queryStr",queryStr);
		}catch(Exception e){
			log.error("查询_收件箱/草稿箱/已发送/已删除/垃圾箱失败，原因是："+e.getMessage(),e);
			return "web/opera_fail";
		}
		return "web/main_list";
	}
	/**
	 * 跳转转发邮件
	 */
	@RequestMapping("/intoForwardingMail")
	public String intoForwardingMail(HttpServletRequest request,HttpServletResponse response,Long idMailDetail){
		try{
			LoginUser loginUser=(LoginUser)request.getSession().getAttribute(Constant.LOGIN_USER);
			//查询邮件明细
			TblMailDetail tblMailDetail=this.tblMailDetailService.getTblMailDetail(idMailDetail);
			SimpleDateFormat f=new SimpleDateFormat("yyyy年MM月dd日 E HH点mm分");
			StringBuffer content = new StringBuffer();
			content.append("<br/>").append("<br/>").append("<br/>")
				.append("<div 0px;color:#000000;text-transform:none;text-indent:0px;letter-spacing:normal;word-spacing:0px;white-space:normal;orphans:2;widows:2;font-size-adjust:none;font-stretch:normal;background-color:#FFFFFF;-webkit-text-size-adjust:auto;-webkit-text-stroke-width:0px;?=\"\" Narrow?;padding:2px=\"\" Arial=\"\">")
				.append("------------------&nbsp;原始邮件&nbsp;------------------")
				.append("</div>")
				.append("<div style=\"font:12px/1.5 Verdana;padding:8px;color:#000000;text-transform:none;text-indent:0px;letter-spacing:normal;word-spacing:0px;white-space:normal;orphans:2;widows:2;font-size-adjust:none;font-stretch:normal;background-color:#EFEFEF;-webkit-text-size-adjust:auto;-webkit-text-stroke-width:0px;\">")
				.append("<div style=\"line-height:1.5;\">")
				.append("<b>发件人:</b> \"").append(tblMailDetail.getSendPeople()).append("\";")
				.append("</div>")
				.append("<div style=\"line-height:1.5;\">")
				.append("<b>发送时间:</b> ").append(f.format(tblMailDetail.getLastDate()))
				.append("</div>")
				.append("<div style=\"line-height:1.5;\">")
				.append("<b>收件人:</b> \"").append(tblMailDetail.getRecPeople()).append("\";")
				.append("</div>")
				.append("<div style=\"line-height:1.5;\">")
				.append("<b>主题:</b> ").append(tblMailDetail.getTitle())
				.append("</div>")
				.append("</div>")
				.append("<br/>");
			tblMailDetail.setContent(content.toString() + tblMailDetail.getContent());
			//收件人
			tblMailDetail.setRecPeople(""); 
			//抄送人
			tblMailDetail.setCopySend("");
			//密送人
			tblMailDetail.setSecretSend("");
			tblMailDetail.setTitle("转发："+tblMailDetail.getTitle());
			//查询附件列表
			List mailAnnexList=this.tblMailAnnexService.getTblMailAnnexList(tblMailDetail.getIdMailAnnex(),null);
			request.setAttribute("tblMailDetail", tblMailDetail);
			request.setAttribute("mailAnnexList", mailAnnexList);
			String idEmployees=(String)request.getSession().getAttribute(Constant.LOGIN_EMPLOYEE);
			//查询所有公司类型
			List tblCompanyTypesList=this.tblCompanyTypesService.getTblCompanyTypesList(idEmployees);
			request.setAttribute("tblCompanyTypesList", tblCompanyTypesList);
			//查询帐号邮箱列表
			request.setAttribute("userMailList",this.tblUserMailService.getTblUserMailList(loginUser.getIdUser()));
		}catch(Exception e){
			log.error("转发邮件失败，原因是："+e.getMessage(),e);
			return "web/opera_fail";
		}
		return "web/send_index";
	}
	
	/**
	 * 详细界面_收件箱/草稿箱/已发送/已删除/垃圾箱
	 */
	@RequestMapping("/queryMailInfo")
	public String queryMailInfo(HttpServletRequest request,HttpServletResponse response,TblMailDetail tblMailDetail,Integer state,Integer pageNo,String queryStr){
		try{
			LoginUser loginUser=(LoginUser)request.getSession().getAttribute(Constant.LOGIN_USER);
			//邮件明细信息，已分页形式显示
			if(StringUtil.isEmpty(pageNo)){
				pageNo=1;
			}
			tblMailDetail.setState(state);
			tblMailDetail.setIdUser(loginUser.getIdUser());
			request.setAttribute("page",this.tblMailDetailService.getTbLMailDetailListInfo(pageNo,Constant.DEFAULT_PAGE_SIZE, tblMailDetail,queryStr));
			//设置为已读
			tblMailDetail=this.tblMailDetailService.getTblMailDetail(tblMailDetail.getIdMailDetail());
			tblMailDetail.setMailSign(1);
			this.tblMailDetailService.saveMailDetail(tblMailDetail);
			//类型转换
			tblMailDetail.setCopySend(StringUtil.reTrimByString(tblMailDetail.getCopySend()).replaceAll("<", "&lt;").replaceAll(">", "&gt;"));
			tblMailDetail.setSecretSend(StringUtil.reTrimByString(tblMailDetail.getSecretSend()).replaceAll("<", "&lt;").replaceAll(">", "&gt;"));
			tblMailDetail.setRecPeople(StringUtil.reTrimByString(tblMailDetail.getRecPeople()).replaceAll("<", "&lt;").replaceAll(">", "&gt;"));
			tblMailDetail.setSendPeople(StringUtil.reTrimByString(tblMailDetail.getSendPeople()).replaceAll("<", "&lt;").replaceAll(">", "&gt;"));
			//收件人
			if(!StringUtil.isEmpty(tblMailDetail.getRecPeople())){
				tblMailDetail.setRecPeople(tblMailDetail.getRecPeople().replaceAll(",", ";"));
			}
			//抄送人
			if(!StringUtil.isEmpty(tblMailDetail.getCopySend())){
				tblMailDetail.setCopySend(tblMailDetail.getCopySend().replaceAll(",", ";"));
			}
			//密送人
			if(!StringUtil.isEmpty(tblMailDetail.getSecretSend())){
				tblMailDetail.setSecretSend(tblMailDetail.getSecretSend().replaceAll(",", ";"));
			}
			SimpleDateFormat f=new SimpleDateFormat("yyyy年MM月dd日 E HH点mm分");
			request.setAttribute("lastdate",f.format(tblMailDetail.getLastDate()));
			request.setAttribute("mailDetail",tblMailDetail);
			//邮件明细关联附件
			request.setAttribute("mailAnnexList",this.tblMailAnnexService.getTblMailAnnexList(tblMailDetail.getIdMailAnnex(), null));
		}catch(Exception e){
			log.error("详细界面_收件箱/草稿箱/已发送/已删除/垃圾箱失败，原因是："+e.getMessage(),e);
			return "web/opera_fail";
		}
		return "web/main_info";
	}
	
	/**
	 * 删除/彻底删除/全部标记为已读/标志为/移动到
	 */
	@RequestMapping("/saveMailDetail")
	public String  saveMailDetail(HttpServletRequest request,HttpServletResponse response,TblMailDetail tblMailDetail,Integer pageNo,Integer curstate,String idMailDetails
			,Integer idCompanyType, Integer idCompany, Integer idContactPerson,String queryStr) {
		try{
			this.tblMailDetailService.updateTbLMailDetail(tblMailDetail, idMailDetails);
			String idEmployees=(String)request.getSession().getAttribute(Constant.LOGIN_EMPLOYEE);
			//查询所有公司类型
			List tblCompanyTypesList=this.tblCompanyTypesService.getTblCompanyTypesList(idEmployees);
			//添加陌生类型
			Map companyType=new HashMap();
			companyType.put("IDCOMPANYTYPE", "0");
			companyType.put("COMPANYTYPENAME", "陌生人");
			tblCompanyTypesList.add(companyType);
			request.setAttribute("tblCompanyTypesList", tblCompanyTypesList);
			//查询邮箱列表
			tblMailDetail.setState(curstate);
			request.setAttribute("page",this.tblMailDetailService.getTbLMailDetailList(pageNo,Constant.DEFAULT_PAGE_SIZE, tblMailDetail,queryStr));
			request.setAttribute("tblMailDetail",tblMailDetail);
			request.setAttribute("idCompanyType",idCompanyType);
			request.setAttribute("idCompany",idCompany);
			request.setAttribute("idContactPerson",idContactPerson);
			request.setAttribute("queryStr",queryStr);
		}catch(Exception e){
			log.error("删除/彻底删除/全部标记为已读/标志为/移动到失败，原因是："+e.getMessage(),e);
			return "web/opera_fail";
		}
		return "web/main_list";
	}
}
